import * as API from '../../api'

export default {
  // 开启命名空间模式
  namespaced: true,
  state: {
    nickname: window.localStorage.getItem('user_nickname') || '',
    avatarurl:window.localStorage.getItem('user_avatarurl') || '',
    token: window.localStorage.getItem('user_token') || '' ,// 用户登录的唯一标识
    userid: window.localStorage.getItem('userid') || '' ,
  },
  getters: {},
  actions: {
    // async函数一定会返回一个promise对象
    // 当async里面代码全部成功执行了，这个promise对象就是成功状态
    // 成功状态结果值就是async函数的返回值（和内部promise无关）
    // 当async里面代码有一个失败了，这个promise对象就是失败状态
    // 失败状态结果值就是错误原因
    async login({ commit }, { phone, password }) {
      const user = await API.login.reqGoLogin(phone, password)
      commit('LOGIN', user)

      // 返回值就是async函数返回的promise的成功结果值
      return {
        user,
        token: user.token,
        nickname: user.profile.nickname,
        avatarurl: user.profile.avatarUrl,
        userid: user.profile.userId,
      }
    }
  },
  mutations: {
    LOGIN(state, user) {
      state.nickname = user.profile.nickname
      state.avatarurl = user.profile.avatarUrl
      state.token = user.token
      state.userid = user.profile.userId


    },
    OUT_LOGIN(state) {
      state.nickname = window.localStorage.setItem('user_nickname','');
      state.avatarurl = window.localStorage.setItem('user_avatarurl','')
      state.token = window.localStorage.setItem('user_token','')
      state.userid = window.localStorage.setItem('userid','')

    }
  }
}
